<template>
  <div class="estimate-management">
    <!-- PPH预估值列表 -->
    <el-card class="list-section">
      <template #header>
        <div class="list-header">
          <span>PPH预估值列表</span>
          <div class="header-actions">
            <el-button @click="exportEstimates" type="success">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
            <el-button @click="loadEstimates" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="primary" @click="generateEstimates" :loading="generating" style="margin-left: 8px;">
              生成预估值
            </el-button>
          </div>

      <div class="next-run" style="margin-bottom: 10px; color: #666;">
        下一次自动生成时间：{{ nextRunDisplay }}（{{ nextRunCountdown }}）
      </div>

        </div>
      </template>

      <!-- 搜索过滤（与目标值管理一致：一行展示） -->
      <el-row :gutter="12" class="search-filters">
        <el-col :span="4">
          <el-input v-model="searchForm.material_code" v-trim-input placeholder="搜索物料编码" clearable style="max-width: 220px; width: 100%" />
        </el-col>
        <el-col :span="4">
          <el-input v-model="searchForm.product_name" v-trim-input placeholder="搜索产品名称" clearable style="max-width: 220px; width: 100%" />
        </el-col>
        <el-col :span="4">
          <LineSelector
            v-model="searchForm.line_name"
            :lines="lines"
            placeholder="筛选生产线"
            :allow-create="true"
            :clearable="true"
            :filterable="true"
          />
        </el-col>
        <el-col :span="4">
          <DateSelector v-model="searchForm.created_date" placeholder="筛选创建日期" :clearable="true" />
        </el-col>
        <el-col :span="8" class="actions-col">
          <el-button @click="queryEstimates" type="primary" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilters" type="default">重置</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        :data="paginatedEstimates"
        stripe
        border
        style="width: 100%"
        v-loading="loading"
        size="small"
      >
        <el-table-column prop="material_code" label="物料编码" :min-width="columnWidths.material_code" show-overflow-tooltip />
        <el-table-column prop="product_name" label="产品名称" :min-width="columnWidths.product_name" show-overflow-tooltip />
        <el-table-column prop="line_name" label="生产线" :min-width="columnWidths.line_name" />
        <el-table-column prop="estimate_pph" label="预估PPH值" :min-width="columnWidths.estimate_pph" align="right" />
        <el-table-column prop="created_at" label="创建时间" :min-width="columnWidths.created_at">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" :min-width="columnWidths.actions" fixed="right">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              @click="deleteEstimate(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="filteredEstimates.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Refresh, Download, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { formatDateTime } from '@/utils/commonUtils'

import DateSelector from '../../components/common/DateSelector.vue'
import LineSelector from '../../components/common/LineSelector.vue'
import { pphService } from '../../services/pphService'
import { useFormDataStore } from '@/stores/formDataStore'

// 引入小屏响应式样式（通过 Vite CSS 处理）
import '/src/styles/estimate-responsive.css'


// 响应式列宽：针对旧式小屏显示器
const columnWidths = computed(() => {
  const w = window.innerWidth || 1366
  // 基于断点的 minWidth 方案
  if (w < 1366) {
    return {
      material_code: 120,
      product_name: 160,
      line_name: 100,
      estimate_pph: 110,
      created_at: 140,
      actions: 100
    }
  } else if (w < 1600) {
    return {
      material_code: 140,
      product_name: 200,
      line_name: 120,
      estimate_pph: 120,
      created_at: 150,
      actions: 110
    }
  } else {
    return {
      material_code: 160,
      product_name: 240,
      line_name: 140,
      estimate_pph: 130,
      created_at: 160,
      actions: 120
    }
  }
})

window.addEventListener('resize', () => {
  // 触发计算属性更新
  pageSize.value = pageSize.value
})


// 下一次生成时间（本地计算）
const nextRunDisplay = ref('计算中...')
const nextRunCountdown = ref('')
let nextRunTimer: any = null

function getNextRunDate(): Date {
  const now = new Date()
  // 计算下一个“每月1号 02:00”
  const y = now.getFullYear()
  const m = now.getMonth()
  const d = now.getDate()
  let target: Date
  if (d === 1 && now.getHours() < 2) {
    target = new Date(y, m, 1, 2, 0, 0, 0)
  } else {
    // 下个月1号 02:00
    target = new Date(y, m + 1, 1, 2, 0, 0, 0)
  }
  return target
}

function formatDate(d: Date): string {
  const y = d.getFullYear()
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  const hh = String(d.getHours()).padStart(2, '0')
  const mi = String(d.getMinutes()).padStart(2, '0')
  return `${y}-${mm}-${dd} ${hh}:${mi}`
}

function updateNextRun() {
  const target = getNextRunDate()
  nextRunDisplay.value = formatDate(target)
  const now = new Date()
  let diff = Math.max(0, target.getTime() - now.getTime())
  const days = Math.floor(diff / (24*60*60*1000)); diff %= 24*60*60*1000
  const hours = Math.floor(diff / (60*60*1000)); diff %= 60*60*1000
  const minutes = Math.floor(diff / (60*1000))
  nextRunCountdown.value = `距离重新生成还有 ${days} 天 ${hours} 小时 ${minutes} 分钟`
}

// 表单数据持久化store
const formDataStore = useFormDataStore()

// 响应式数据
const loading = ref(false)
const generating = ref(false)
const estimates = ref<any[]>([])
const lines = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  material_code: '',
  product_name: '',
  line_name: '',
  created_date: ''
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)


// 计算属性 - 现在只用于显示，实际筛选在后端进行
const filteredEstimates = computed(() => {
  return Array.isArray(estimates.value) ? estimates.value : []
})

// 计算属性 - 分页后的数据
const paginatedEstimates = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredEstimates.value.slice(start, end)
})

// 加载生产线数据
async function loadLines() {
  try {
    const response = await pphService.getLines()
    lines.value = response.lines || []
  } catch (error: any) {
    console.error('获取生产线列表失败:', error)
    ElMessage.error('获取生产线列表失败: ' + (error?.message || String(error)))
    lines.value = []
  }
}

// 加载预估值数据
async function loadEstimates() {
  try {
    loading.value = true
    const apiUrl = `${pphService.getApiUrl()}/api/estimates`
    console.log('🔍 加载预估值数据，API地址:', apiUrl)
    const response = await fetch(apiUrl)
    if (response.ok) {
      const data = await response.json()
      estimates.value = Array.isArray(data) ? data : []
      console.log('✅ 预估值数据加载成功:', estimates.value.length, '条')
    } else {
      console.error('❌ 预估值数据加载失败，状态码:', response.status)
      ElMessage.error('加载预估值数据失败')
      estimates.value = []
    }
  } catch (error: any) {
    console.error('❌ 加载预估值数据失败:', error)
    ElMessage.error('加载预估值数据失败: ' + (error?.message || String(error)))
    estimates.value = []
  } finally {
    loading.value = false
  }
}

// 生成预估值
async function generateEstimates() {
  try {
    generating.value = true
    const apiUrl = `${pphService.getApiUrl()}/api/estimates/generate`
    console.log('🛠️ 生成预估值，API地址:', apiUrl)
    const response = await fetch(apiUrl, { method: 'POST' })
    if (!response.ok) {
      const error = await response.json().catch(() => ({}))
      throw new Error(error.error || '生成失败')
    }
    const data = await response.json().catch(() => ({}))
    const from = data?.window?.from || '-'
    const to = data?.window?.to || '-'
    const method = data?.method || 'weighted-person-hours'
    ElMessage.success(`生成成功（窗口：${from} 至 ${to}，方法：${method}）：写入 ${data.inserted ?? 0} 条`)
    await loadEstimates()
  } catch (error: any) {
    ElMessage.error('生成失败: ' + (error?.message || String(error)))
  } finally {
    generating.value = false
  }
}


// 查询预估值数据
async function queryEstimates() {
  try {
    loading.value = true

    // 构建查询参数
    const params = new URLSearchParams()
    if (searchForm.material_code) params.append('material_code', searchForm.material_code)
    if (searchForm.product_name) params.append('product_name', searchForm.product_name)
    if (searchForm.line_name) params.append('line_name', searchForm.line_name)
    if (searchForm.created_date) params.append('created_date', searchForm.created_date)

    const baseUrl = `${pphService.getApiUrl()}/api/estimates`
    const url = params.toString() ? `${baseUrl}?${params.toString()}` : baseUrl
    console.log('🔍 查询预估值，API地址:', url)
    const response = await fetch(url)

    if (response.ok) {
      const data = await response.json()
      estimates.value = Array.isArray(data) ? data : []
      currentPage.value = 1 // 重置到第一页
      } else {
      ElMessage.error('查询预估值数据失败')
      estimates.value = []
    }
  } catch (error: any) {
    console.error('查询预估值数据失败:', error)
    ElMessage.error('查询失败: ' + (error?.message || String(error)))
    estimates.value = []
  } finally {
    loading.value = false
  }
}

// ✅ formatDateTime函数已重构到 utils/commonUtils.ts

// 重置筛选条件
function resetFilters() {
  searchForm.material_code = ''
  searchForm.product_name = ''
  searchForm.line_name = ''
  searchForm.created_date = ''
  estimates.value = [] // 清空数据，需要用户手动查询
}

// 处理搜索过滤器事件
// 已去除复合筛选组件事件，统一使用本页查询与重置按钮

// Excel导出逻辑 - 调用后端Excel导出API
async function exportEstimates() {
  try {
    loading.value = true

    console.log('📊 开始导出预估值数据...')

    // 使用当前筛选的数据
    const dataToExport = filteredEstimates.value

    if (dataToExport.length === 0) {
      ElMessage.warning('没有数据可以导出')
      return
    }

    console.log(`📊 准备导出 ${dataToExport.length} 条预估值数据`)

    // 调用后端Excel导出API
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/excel/export/estimates`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      },
      body: JSON.stringify({ estimates: dataToExport })
    })

    if (!response.ok) {
      const error = await response.json().catch(() => ({}))
      throw new Error(error.error || `导出失败: ${response.status}`)
    }

    // 获取文件名并下载
    const contentDisposition = response.headers.get('Content-Disposition')
    let filename = `PPH预估值数据_${new Date().toISOString().split('T')[0]}.xlsx`
    if (contentDisposition) {
      const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (match && match[1]) {
        filename = match[1].replace(/['"]/g, '')
      }
    }

    // 下载文件
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success(`Excel导出成功: ${filename}`)
  } catch (error: any) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + (error?.message || String(error)))
  } finally {
    loading.value = false
  }
}

// 删除预估值
async function deleteEstimate(id: number) {
  try {
    await ElMessageBox.confirm('确定要删除这条预估值记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const apiUrl = `${pphService.getApiUrl()}/api/estimates/${id}`
    console.log('🗑️ 删除预估值，API地址:', apiUrl)
    const response = await fetch(apiUrl, {
      method: 'DELETE'
    })

    if (response.ok) {
      ElMessage.success('删除成功')
      await loadEstimates()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error?.message || String(error)))
    }
  }
}

// 分页处理
function handleSizeChange(val: number) {
  pageSize.value = val
  currentPage.value = 1
}

function handleCurrentChange(val: number) {
  currentPage.value = val
}

// 保存搜索表单数据
function saveSearchFormData() {
  formDataStore.saveSearchForm('estimate', searchForm)
  formDataStore.savePageState('estimateManagement', {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    lastSearchParams: { ...searchForm }
  })
}

// 恢复搜索表单数据
function restoreSearchFormData() {
  const savedForm = formDataStore.getSearchForm('estimate')
  const hasValidData = savedForm && Object.keys(savedForm).some(key => {
    const value = savedForm[key]
    return value !== '' && value !== null && value !== undefined
  })

  if (hasValidData) {
    console.log('🔄 恢复预估值页面保存的搜索条件:', savedForm)
    Object.assign(searchForm, savedForm)

    const pageState = formDataStore.getPageState('estimateManagement')
    if (pageState.currentPage) {
      currentPage.value = pageState.currentPage
    }
    if (pageState.pageSize) {
      pageSize.value = pageState.pageSize
    }

    ElMessage.success('已恢复上次的搜索条件')

    // 预估值页面需要自动执行搜索，因为用户期望看到数据列表
    setTimeout(() => {
      queryEstimates()
    }, 100)
  } else {
    console.log('📝 预估值页面没有有效的保存状态')
    // 智能加载策略：不自动加载所有数据，等待用户操作
    // 用户可以：1) 输入查询条件进行搜索 2) 点击"生成预估值"按钮
    console.log('💡 预估值管理页面已加载，请输入查询条件或点击"生成预估值"按钮')
  }
}


// 监听搜索表单变化，自动保存
watch(() => searchForm, saveSearchFormData, { deep: true })
watch(() => currentPage.value, saveSearchFormData)
watch(() => pageSize.value, saveSearchFormData)



// 生命周期 - 只加载生产线数据，不自动加载预估值数据
onMounted(async () => {
  await loadLines()
  updateNextRun()
  if (nextRunTimer) clearInterval(nextRunTimer)
  nextRunTimer = setInterval(updateNextRun, 60*1000)
  // 恢复搜索表单数据
  restoreSearchFormData()
})
</script>

<style scoped>
.estimate-management {
  padding: 20px;
}

/* ✅ 列表头部、分页、表单区域样式已移至公共样式 common.css */

.search-filters :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-filters .actions-col {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-start;
}

.search-filters { margin-bottom: 8px; }
.search-filters .actions-col .el-button + .el-button { margin-left: 8px; }
.search-filters :deep(.el-form-item__label) { padding-right: 6px; }
.search-filters :deep(.el-input),
.search-filters :deep(.el-select),
.search-filters :deep(.el-date-editor) {
  --el-input-height: 30px;
}
</style>
